package com.shop.cloud.service.hongfu.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shop.cloud.JPush.MsgPushUtils;
import com.shop.cloud.common.mybatis.BaseService;
import com.shop.cloud.common.mybatis.MybatisDao;
import com.shop.cloud.dao.hongfu.ActivityDao;
import com.shop.cloud.dao.hongfu.ActivityEnrollDao;
import com.shop.cloud.dao.hongfu.DistributionInstallDao;
import com.shop.cloud.domain.hongfu.Activity;
import com.shop.cloud.domain.hongfu.ActivityEnroll;
import com.shop.cloud.domain.hongfu.BalanceHistory;
import com.shop.cloud.domain.hongfu.DistributionInstall;
import com.shop.cloud.domain.hongfu.User;
import com.shop.cloud.service.hongfu.IActivityEnrollService;
import com.shop.cloud.service.hongfu.IActivityService;
import com.shop.cloud.service.hongfu.IBalanceHistoryService;
import com.shop.cloud.service.hongfu.IDistributionInstallService;
import com.shop.cloud.service.hongfu.IDistributionMsgService;
import com.shop.cloud.service.hongfu.IUserService;
import com.shop.cloud.util.Page;

import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;

/**
 * activity
 */
@Transactional
@Service("activityService")
public class ActivityService extends BaseService<Activity> implements IActivityService{
    
    @Autowired
	private ActivityDao activityDao;
    
    @Autowired
	private IActivityEnrollService activityEnrollService;
    
    @Autowired
    private ActivityEnrollDao activityEnrollDao;
    
    @Autowired
    private IDistributionInstallService distributionInstallService;
    
    @Autowired
    private DistributionInstallDao distributionInstallDao;
    
    @Autowired
    private IUserService userService;
    
    @Autowired
    private IDistributionMsgService distributionMsgService;
    
    @Autowired
    private IBalanceHistoryService balanceHistoryService;

	@Override
	public MybatisDao<Activity> getEntityDao() {
		return activityDao;
	}
	
	public int updateByTime(final Map<String, Object> params) {
		return activityDao.updateByTime(params);
	}
	
	@Override
	public Activity handleActivity(Long userId, String activityID) {
		
		Activity insActivity = new Activity();
		
		if(StringUtils.isNotEmpty(activityID)){
			insActivity = this.get(new Long(activityID));
			
			//处理分销信息
			if(insActivity.getDistributeType() == 0){
				DistributionInstall distributionInstall = distributionInstallDao.getByTypeAndUser(new Long(activityID));
				if(null != distributionInstall){
					String distributionString = distributionInstall.getDistriSetting();
					if(StringUtils.isNotEmpty(distributionString)){
						try {
							JSONArray jsonArray = new JSONArray(distributionString);
							for(int i = 0; i < jsonArray.length(); i ++){
								JSONObject jsonObject = jsonArray.getJSONObject(i);
								String descName = jsonObject.getString("desc_name");
								if(StringUtils.isNotEmpty(descName) && "一级".equals(descName)){
									insActivity.setDistributeValueOne(jsonObject.getString("desc_value"));
								}
								if(StringUtils.isNotEmpty(descName) && "二级".equals(descName)){
									insActivity.setDistributeValueTwo(jsonObject.getString("desc_value"));
								}
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}
			}
			
			//处理报名信息
			ActivityEnroll activityEnroll = new ActivityEnroll(); 
			activityEnroll.setActivityId(new Long(activityID));
			List<ActivityEnroll> dataList = activityEnrollService.find(activityEnroll);
			insActivity.setExistNum(dataList.size());
			if(null != dataList && dataList.size() > 0){
				for(int i = 0; i < dataList.size(); i ++){
					ActivityEnroll insData = dataList.get(i);
					if(userId == insData.getUserId()){
						insActivity.setReadyJoin(1);
						break;
					}
				}
			}
		}
		
		return insActivity;
	}
	
	@Override
	public boolean handleInsertActivity(Activity activity) {
		boolean flag = false;
		
		//订单号
		String orderNo = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ((int)((Math.random()*9+1)*100000));
		
		activity.setOrderNo(orderNo);
		activity.setCreateTime(new Timestamp((new Date()).getTime()));
		flag = this.insert(activity);
		
		String distributionString = activity.getDistributionString();
		distributionInstallService.handleInsertDistributionInstall(distributionString, 1, activity.getId());
		
		return flag;
	}
	
	@Override
	public int handleDeleteActivity(String activityID) {
		
		int resultInt = 0;
		
		if(StringUtils.isNotEmpty(activityID)){
			Activity insActivity = this.get(new Long(activityID));
			insActivity.setExistFlag(1);
			
			resultInt = this.update(insActivity);
		}
		
		return resultInt;
	}

	@Override
	public Activity handleActivityAndEnroll(String activityID) {
		
		Activity insActivity = new Activity();
		
		if(StringUtils.isNotEmpty(activityID)){
			insActivity = this.get(new Long(activityID));
			
			ActivityEnroll activityEnroll = new ActivityEnroll();
			activityEnroll.setActivityId(new Long(activityID));
			List<ActivityEnroll> dataList = activityEnrollService.find(activityEnroll);
			
			insActivity.setActivityEnroll(dataList);
			
			if(insActivity.getDistributeType() == 0){
				DistributionInstall distributionInstall = distributionInstallDao.getByTypeAndUser(new Long(activityID));
				if(null != distributionInstall){
					String distributionString = distributionInstall.getDistriSetting();
					if(StringUtils.isNotEmpty(distributionString)){
						try {
							JSONArray jsonArray = new JSONArray(distributionString);
							for(int i = 0; i < jsonArray.length(); i ++){
								JSONObject jsonObject = jsonArray.getJSONObject(i);
								String descName = jsonObject.getString("desc_name");
								if(StringUtils.isNotEmpty(descName) && "一级".equals(descName)){
									insActivity.setDistributeValueOne(jsonObject.getString("desc_value"));
								}
								if(StringUtils.isNotEmpty(descName) && "二级".equals(descName)){
									insActivity.setDistributeValueTwo(jsonObject.getString("desc_value"));
								}
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		
		return insActivity;
	}

	@Override
	public List<ActivityEnroll> handleActivityUserList(String activityID) {
		
		Activity insActivity = this.handleActivityAndEnroll(activityID);
		if(null != insActivity){
			List<ActivityEnroll> insEnrolls = insActivity.getActivityEnroll();
			if(null != insEnrolls && insEnrolls.size() > 0){
				for(ActivityEnroll enroll : insEnrolls){
					Long userId = enroll.getUserId();
					User insUser = userService.get(userId);
					if(null != insUser){
						enroll.setUserName(insUser.getNickname());
						enroll.setUserMobile(insUser.getPhone());
						enroll.setAmount(insActivity.getPrice());
					}
				}
			}
			return insEnrolls;
		}else{
			return null;
		}
	}

	@Override
	public int handleUpdateActivity(Activity activity) {
		int resultInt = 0;
		
		resultInt = this.update(activity);
		
		String distributionString = activity.getDistributionString();
		distributionInstallService.handleModifyDistributionInstall(distributionString, 1, activity.getId());
		
		return resultInt;
	}

	@Override
	public Page<Activity> getPage(Long userID, Activity activity) {
		
		//分页请求参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userID);
		params.put("orderBy", activity.getOrderBy());
		params.put("limitStart", activity.getLimitStart());
		params.put("limitEnd", activity.getLimitEnd());
		
		long count = activityDao.countMyActivity(params);
		if(null == activity.getPageSize_()){
			Page<Activity> page = new Page<Activity>(activity.getPageIndex_(), 10);
			page.setData(activityDao.findMyActivity(params));
			page.setTotalCount(count);
			
			return page;
		}else{
			Page<Activity> page = new Page<Activity>(activity.getPageIndex_(), activity.getPageSize_());
			page.setData(activityDao.findMyActivity(params));
			page.setTotalCount(count);
			
			return page;
		}
		
	}

	@Override
	public int handleActivityEnroll(Long userID, String activityID) {
		//获取参加活动用户
		User user = userService.get(userID);
		//获取参加的活动详情
		Activity activity = this.get(new Long(activityID));
		
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("userId", userID);
		hashMap.put("activityId", activityID);
		long count = activityEnrollDao.count(hashMap);
		if(count>0){
			return 3;
		}
		
		//减去参加活动所花的余额
		float balance = user.getBalance();
		float price = activity.getPrice();
		if(price > balance){
			//用户余额不足
			return 1;
		}
		if(price > 0){
			user.setBalance(balance - price);
		}
		userService.update(user);
		//处理报名人数剩余
		int restrictNum = activity.getRestrictNum();
		if(restrictNum != 0){
			activity.setRestrictNum(restrictNum - 1);
			this.update(activity);
		}
		
		//处理财务流水
		BalanceHistory balanceHistory = new BalanceHistory();
		balanceHistory.setUserId(userID);
		balanceHistory.setType(12);
		balanceHistory.setAmount(price);
		balanceHistory.setActivityId(new Long(activityID));
		balanceHistory.setOrderNo(activity.getOrderNo());
		balanceHistory.setCreateTime(new Timestamp((new Date()).getTime()));
		balanceHistory.setRemark(user.getNickname()+"参加活动，报名费:"+price+"元。");
		//创建流水
		balanceHistoryService.insert(balanceHistory);
		
		//处理分销所得
		distributionMsgService.handleJoinActivity(userID.toString(), activityID);
		
		ActivityEnroll activityEnroll = new ActivityEnroll();
		activityEnroll.setUserId(userID);
		activityEnroll.setActivityId(new Long(activityID));
		activityEnroll.setEnrollTime(new Timestamp((new Date()).getTime()));
		
		boolean result = activityEnrollService.insert(activityEnroll);
		
		if(result){
			return 0;
		}else {
			return 2;
		}
	}

	@Override
	public void handleActivityEnd() {
		Timestamp thisTime = new Timestamp((new Date()).getTime());
		//判断活动是否已结束
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("thisTime", thisTime);
		activityDao.updateThisEnd(params);
	}

	@Override
	public void handleActivityStart() {
		Timestamp thisTime = new Timestamp((new Date()).getTime());
		//判断活动是否已开始
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("thisTime", thisTime);
		activityDao.updateThisStart(params);
	}

	@Override
	public void handleActivityRefund(String activityID, Long userId) {
		//获取参加的活动详情
		Activity activity = this.get(new Long(activityID));
		
		//先删除报名表中信息
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
		params.put("activityID", activityID);
		activityEnrollDao.removeThisByUserAndAc(params);
		
		//再修改活动表中人数
		if(null != activity){
			int restrictNum = activity.getRestrictNum();
			if(restrictNum > 0){
				activity.setRestrictNum(restrictNum + 1);
				this.update(activity);
			}
		}
		//归还活动报名费
		//获取参加活动用户
		User user = userService.get(userId);
		if(null != activity){
			Float price = activity.getPrice();
			if(price > 0){
				user.setBalance(user.getBalance() + price);
				userService.update(user);
				
				//处理财务流水
				BalanceHistory balanceHistory = new BalanceHistory();
				balanceHistory.setUserId(userId);
				balanceHistory.setType(15);
				balanceHistory.setAmount(price);
				balanceHistory.setActivityId(new Long(activityID));
				balanceHistory.setCreateTime(new Timestamp((new Date()).getTime()));
				balanceHistory.setRemark(user.getNickname()+"活动退款:"+price+"元。");
				//创建流水
				balanceHistoryService.insert(balanceHistory);
			}
			
			//极光推送
			try {
				MsgPushUtils.addJPush("您在"+activity.getTitle()+"活动的报名已退款", userId.toString());
			} catch (APIConnectionException e) {
				e.printStackTrace();
			} catch (APIRequestException e) {
				e.printStackTrace();
			}
		}
	}
    
}